import {
  constantRoutes
} from '@/router'
import {
  getRouters
} from '@/api/menu'
import Layout from '@/layout/index'

const permission = {
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = []
      state.routes = routes
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({
      commit
    }, roles = []) {
      return new Promise(resolve => {

        // 过滤后的菜单
        let myMenu = filterMenu(constantRoutes, roles)
        myMenu = filterNoChilrenMenu(myMenu);
        // 向后端请求路由数据
        // getRouters().then(res => {
        //   const accessedRoutes = filterAsyncRouter(res.data)
        //   accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
        //   commit('SET_ROUTES', accessedRoutes)
        //   resolve(accessedRoutes)
        // })
        console.log(myMenu);
        commit('SET_ROUTES', myMenu)
        resolve([])
      })
    }
  }
}


// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.roles) {

    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}
const filterMenu = (menuList, roleCode) => {
  return menuList.filter(item => {
    if (!item.meta || !item.meta.authRole) {
      return true;
    }
    let roles = roleCode;
    return (item.meta && item.meta.authRole && item.meta.authRole.some(x =>
      roles.indexOf(x) !== -1
    ));
  }).map(item => {
    item = Object.assign({}, item)
    if (item.children) {
      item.children = filterMenu(item.children, roleCode)
    }
    return item
  })
}

const filterNoChilrenMenu = (menuList) => {
  return menuList.filter(item => {
    if (item.component && item.component.name && item.component.name == 'Layout' && item.children.length == 0) {
      return false;
    }
    return true;
  }).map(item => {
    item = Object.assign({}, item)
    if (item.children) {
      item.children = filterNoChilrenMenu(item.children)
    }
    return item
  })
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permission
